package com.ce.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ce.server.common.RespBean;
import com.ce.server.pojo.*;
import com.ce.server.service.IMenuRoleService;
import com.ce.server.service.IMenuService;
import com.ce.server.service.IOperlogService;
import com.ce.server.service.IRoleService;
import com.ce.server.util.AdminUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组
 *
 * @DATE: 2021/11/21 17:16
 * @Author: 小爽帅到拖网速
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissController {

  @Autowired
  private IRoleService roleService;
  @Autowired
  private IMenuService menuService;
  @Autowired
  private IMenuRoleService menuRoleService;
  @Autowired
  private IOperlogService operlogService;

  @ApiOperation(value = "获取所有角色")
  @GetMapping("/")
  public List<Role> getAllRoles(){
    return roleService.list();
  }

  @ApiOperation(value = "添加角色")
  @PostMapping("/")
  public RespBean addRole(@RequestBody Role role){
    if (!role.getName().startsWith("ROLE_")){
      role.setName("ROLE_"+role.getName());
    }
    if (roleService.save(role)){
      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("添加新的角色信息").setOpertime(LocalDateTime.now()));
      return RespBean.success("添加角色成功！");
    }
    return RespBean.error("添加角色失败！");
  }

  @ApiOperation(value = "删除角色")
  @DeleteMapping("/role/{rid}")
  public RespBean deleteRole(@PathVariable Integer rid){
    if (roleService.removeById(rid)){
      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("根据id删除了角色信息").setOpertime(LocalDateTime.now()));
      return RespBean.success("删除角色成功！");
    }
    return RespBean.error("删除角色失败");
  }

  @ApiOperation(value = "查询所有菜单")
  @GetMapping("/menus")
  public List<Menu> getAllMenus(){
    return menuService.getAllMenus();
  }

  @ApiOperation(value = "根据角色id查询菜单id")
  @GetMapping("/mid/{rid}")
  public List<Integer> getMidByRid(@PathVariable Integer rid){
    List<Integer> mids = menuRoleService.list(new LambdaQueryWrapper<MenuRole>().eq(MenuRole::getRid, rid))
            .stream().map(MenuRole::getMid).collect(Collectors.toList());
    return mids;
  }

  @ApiOperation(value = "更新角色菜单")
  @PutMapping("/")
  public RespBean updateMenuRole(Integer rid,Integer[] mids){
    return menuRoleService.updateMenuRole(rid,mids);
  }
}
